package com.aya.export.aspect;

import com.aya.export.finder.PropertyFinder;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

/**
 * @author ls9527
 * @date 2025/3/2
 */
public class PageSwitcher {
    // 暂时强制使用第一个参数的值+1
    public Object[] nextPage(Object[] arguments, String pageNoDescription) {
        Switcher switcher = null;
        if (pageNoDescription.equalsIgnoreCase("base")) {
            switcher = new PageBaseSwitcher(arguments);
        }
        final String[] split = pageNoDescription.split(":");
        if (split.length == 2 && split[0].equalsIgnoreCase("nested")) {
            final String pageNoPosition = split[1];
            switcher = new PageNestedSwitcher(arguments, pageNoPosition);
        }
        if (switcher == null) {
            throw new RuntimeException("错误的分页规则,无法分页");
        }
        switcher.nextPage();
        return arguments;
    }

    public void resetPage(Object[] arguments, String pageNoDescription) {
        setPageNo(arguments, pageNoDescription, 1);
    }

    private void setPageNo(Object[] arguments, String pageNoDescription, int pageNo) {

    }

    private interface Switcher{

        void nextPage();

        void resetPage();
    }
    private class PageBaseSwitcher implements Switcher{

        private final Object[] arguments;

        public PageBaseSwitcher(Object[] arguments) {
            this.arguments = arguments;
        }

        @Override
        public void nextPage() {
            arguments[0] = (int) arguments[0] + 1;
        }

        @Override
        public void resetPage() {
            arguments[0] = 1;
        }

    }

    private class PageNestedSwitcher implements Switcher{

        private final Object[] arguments;
        private final String pageNoPosition;

        public PageNestedSwitcher(Object[] arguments, String pageNoPosition) {
            this.arguments = arguments;
            this.pageNoPosition = pageNoPosition;
        }

        @Override
        public void nextPage() {
            final Object argument = arguments[0];
            final Object nestedProperty = PropertyFinder.getNestedProperty(argument, pageNoPosition);
            BeanWrapper beanWrapper = new BeanWrapperImpl(argument);
            beanWrapper.setPropertyValue(pageNoPosition, (int) nestedProperty + 1);
        }

        @Override
        public void resetPage() {
            final Object argument = arguments[0];
            BeanWrapper beanWrapper = new BeanWrapperImpl(argument);
            beanWrapper.setPropertyValue(pageNoPosition, 1);
        }
    }
}
